#include <sstream>
#include "TestQuery.h"

using namespace std;


void TextQuery::store_file(ifstream& is)
{
	string textLine;
	while(getline(is, textLine))
		_content.push_back(textLine);
}

void TextQuery::build_map()
{
	// process each line from the input vector
	for(line_no line_num = 0; line_num != _content.size(); ++ line_num)
	{
		// will use line to read the text a word at a time
		istringstream line(_content[line_num]);
		string word;
		while(line >> word)
			// add this line number to the set;
			// subscript will add word to the map if it's not already there
			_wordMap[word].insert(line_num);
	}
}

set<TextQuery::line_no> TextQuery::run_query(const string &query_word) const
{
	map<string, set<line_no>>::const_iterator loc = _wordMap.find(query_word);
	
	if(loc == _wordMap.end())
		return set<line_no>(); // not found, return empty set
	else
		return loc->second; // fetch and return set of line numbers for this word

}

string TextQuery::text_line(line_no line) const
{
	if(line < _content.size())
		return _content[line];
	throw out_of_range("line number out of range.");
}